const express = require('express');
const router = express.Router();
const StockService = require('../services/StockService');
const StockHistoryService = require('../services/StockHistoryService');
const stockDataScheduler = require('../services/StockDataScheduler');
const LevelDBService = require('../services/LevelDBService');

// 获取所有股票
router.get('/', (req, res) => {
  try {
    const stocks = StockService.getAllStocks();
    res.json(stocks);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 获取所有股票信息（从数据库）
router.get('/info', async (req, res) => {
  try {
    const stocks = await LevelDBService.getAllStocks();
    res.json(stocks);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 根据市场类型获取股票信息
router.get('/info/:market', async (req, res) => {
  try {
    const { market } = req.params;
    const stocks = await LevelDBService.getStocksByMarket(market.toUpperCase());
    res.json(stocks);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 搜索股票信息
router.get('/info/search/:keyword', async (req, res) => {
  try {
    const { keyword } = req.params;
    const stocks = await LevelDBService.searchStocks(keyword);
    res.json(stocks);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 根据股票代码获取股票信息
router.get('/:symbol', async (req, res) => {
  try {
    const { symbol } = req.params;
    const stock = StockService.getStockBySymbol(symbol);
    
    if (!stock) {
      return res.status(404).json({ error: 'Stock not found' });
    }
    
    res.json(stock);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 获取股票实时数据
router.get('/:symbol/realtime', async (req, res) => {
  try {
    const { symbol } = req.params;
    const realData = await StockService.getRealStockData(symbol);
    res.json(realData);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 获取多只股票的实时数据
router.post('/realtime/batch', async (req, res) => {
  try {
    const { symbols } = req.body;
    if (!symbols || !Array.isArray(symbols)) {
      return res.status(400).json({ error: 'Symbols array is required' });
    }
    
    const realData = await StockService.getMultipleRealStockData(symbols);
    res.json(realData);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 获取股票历史数据
router.get('/:symbol/history', async (req, res) => {
  try {
    const { symbol } = req.params;
    const { limit = 100 } = req.query;
    
    console.log(`Received request for history data of ${symbol} with limit ${limit}`);
    const historyData = await StockHistoryService.getHistoricalData(symbol, 'daily', parseInt(limit));
    
    // 添加响应头以提供更多上下文
    res.set('X-Data-Source', historyData.length > 0 && historyData[0].hasOwnProperty('id') ? 'database' : 'api');
    
    res.json({
      success: true,
      data: historyData,
      source: historyData.length > 0 && historyData[0].hasOwnProperty('id') ? 'database' : 'api',
      count: historyData.length
    });
  } catch (error) {
    console.error(`Error fetching history data for ${symbol}:`, error.message);
    res.status(500).json({ 
      success: false,
      error: error.message,
      source: 'api'
    });
  }
});

// 手动更新股票历史数据
router.post('/:symbol/history/update', async (req, res) => {
  try {
    const { symbol } = req.params;
    
    console.log(`Received request to update history data for ${symbol}`);
    const historyData = await StockHistoryService.fetchAndStoreHistory(symbol, 'daily');
    
    res.json({
      success: true,
      message: `Successfully updated ${historyData.length} records for ${symbol}`,
      count: historyData.length,
      data: historyData.slice(-5) // 只返回最后5条记录作为示例
    });
  } catch (error) {
    console.error(`Error updating history data for ${symbol}:`, error.message);
    // 直接返回错误，不使用模拟数据
    res.status(500).json({ 
      success: false,
      error: error.message
    });
  }
});

// 手动触发所有关注股票的历史数据更新
router.post('/history/update-all', async (req, res) => {
  try {
    console.log('Received request to update all watched stocks');
    await stockDataScheduler.updateAllStocks();
    res.json({ 
      success: true,
      message: 'Successfully triggered update for all watched stocks' 
    });
  } catch (error) {
    console.error('Error updating all watched stocks:', error.message);
    res.status(500).json({ 
      success: false,
      error: error.message
    });
  }
});

// 设置关注的股票列表
router.post('/watchlist', (req, res) => {
  try {
    const { symbols } = req.body;
    if (!symbols || !Array.isArray(symbols)) {
      return res.status(400).json({ 
        success: false,
        error: 'Symbols array is required' 
      });
    }
    
    stockDataScheduler.setWatchlist(symbols);
    res.json({ 
      success: true,
      message: 'Watchlist updated successfully', 
      watchlist: symbols 
    });
  } catch (error) {
    console.error('Error updating watchlist:', error.message);
    res.status(500).json({ 
      success: false,
      error: error.message 
    });
  }
});

// 获取当前关注的股票列表
router.get('/watchlist', (req, res) => {
  try {
    res.json({ 
      success: true,
      watchlist: stockDataScheduler.watchlist 
    });
  } catch (error) {
    console.error('Error fetching watchlist:', error.message);
    res.status(500).json({ 
      success: false,
      error: error.message 
    });
  }
});

module.exports = router;